package com.buho29.rcmanager;

import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.bd.TablePower;
import com.buho29.rcmanager.bd.TablePowerItem;
import com.buho29.rcmanager.utils.Make;

public class PowersView extends ListActivity {
	
    public static final int CMD_MODEL =1;
    public static final int CMD_FIND =2;
    public static final int CMD_ALL =3;
    
    public static final String CMD="cmd";
    
    // menu
    private static final int NEW_POWER_ID = Menu.FIRST;
    private static final int FIND_POWER_ID = Menu.FIRST +5;
    private static final int FIND_POWER_ALL = Menu.FIRST +6;
    
    // menu item
    private static final int DELETE_ID = Menu.FIRST +1;
    private static final int DELETEITEM_ID = Menu.FIRST +2;
    private static final int EDIT_ID = Menu.FIRST + 3;
    private static final int STATISTIC_ID = Menu.FIRST + 4;
    // launche activity
    private static final int ACTIVITY_NEW= 1;
    private static final int ACTIVITY_EDIT=2;
    private static final int ACTIVITY_FIND=3;
    private static final int ACTIVITY_FIND_ALL=4;
	private static final int ACTIVITY_CHRONO = 5;
	private static final int ACTIVITY_STATISTIC = 6;
    
	private DatabaseAdapter mDbAdapter;
	private TablePower mDbTablePower = new TablePower();
	private TablePowerItem mDbTablePowerItem = new TablePowerItem();
	
	private Long mModelId;
	private int mCmd;

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.power_view);
        
        mDbAdapter = DatabaseAdapter.getInstance(this); 
        mDbTablePower.setSQLiteDatabase(mDbAdapter.getDatabase());
        mDbTablePowerItem.setSQLiteDatabase(mDbAdapter.getDatabase());
     	
		Bundle extras = getIntent().getExtras();            
		if(extras != null){
			mCmd = extras.getInt(CMD);
			mModelId = extras.getLong(TableModel.COL_ROW_ID);
		}else if(savedInstanceState != null){
			mCmd = savedInstanceState.getInt(CMD);
	       	mModelId = savedInstanceState.getLong(TableModel.COL_ROW_ID);
		}
        
        registerForContextMenu(getListView());
        populateFields();
        //Log.d("TAG",Format.formatDecisecondsToString(1806));
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TableModel.COL_ROW_ID, mModelId);
        outState.putLong(CMD, mCmd);
    }
    
    private void populateFields() {
        
    	Cursor cur;
		if(mCmd == CMD_FIND){
			cur = mDbTablePower.fetchPowersAvailable(mModelId);
			setTitle(R.string.find);
		}else if(mCmd == CMD_MODEL){
    		cur = mDbTablePower.fetchPowers(mModelId);
    		TableModel tm = new TableModel();
    		tm.setSQLiteDatabase(mDbAdapter.getDatabase());
    		tm.setId(mModelId);
    		tm.load();
    		setTitle(tm.getName());
    	}else {
    		cur = mDbTablePowerItem.retrieveAll();
			setTitle(R.string.all);
    	}
		
    	startManagingCursor(cur);

    	
        setListAdapter(new PowerAdapter(this,cur));
    }

	/****************************************************************************/
    
	private void launchChrono(long powerId) {
	    Intent i = new Intent(this, ChronoView.class);
	    i.putExtra(TablePowerItem.COL_ROW_ID, powerId);
	    i.putExtra(CMD, ChronoView.CMD_1);
		//i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	    startActivityForResult(i, ACTIVITY_CHRONO); 
	}

	private void launchStatistic(long powerItemID) {
		Intent i = new Intent(this, PowerItemView.class);
		i.putExtra(TablePowerItem.COL_ROW_ID, powerItemID);
		i.putExtra(CMD, 1);
		startActivityForResult(i, ACTIVITY_STATISTIC);
	}
	
    private void createPower(){
    	Intent i = new Intent(this, PowerEdit.class);
		i.putExtra(CMD, TablePowerItem.CMD_NEW);
		startActivityForResult(i, ACTIVITY_NEW);
    }

	private void findPower() {
		Intent i = new Intent(this, PowersView.class);
		i.putExtra(CMD, PowersView.CMD_FIND);
		i.putExtra(TablePowerItem.COL_ROW_ID, mModelId);
		startActivityForResult(i, ACTIVITY_FIND);
	}
	
    private void findPowerAll() {
		Intent i = new Intent(this, PowersView.class);
		i.putExtra(CMD, PowersView.CMD_ALL);
		startActivityForResult(i, ACTIVITY_FIND_ALL);
	}

	private void launchEdit(long powerItemID) {
		Intent i = new Intent(this, PowerEdit.class);
		i.putExtra(TablePower.COL_ROW_ID, powerItemID);
		i.putExtra(CMD, TablePower.CMD_EDIT);
		startActivityForResult(i, ACTIVITY_EDIT);
	}
	
	/***************************************************************************/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, NEW_POWER_ID,0, getString(R.string.New));
        if(mCmd == CMD_MODEL){
        	menu.add(0, FIND_POWER_ID,0, getString(R.string.find));
        	menu.add(0, FIND_POWER_ALL,0, getString(R.string.all));
        }
        return true;
    }   
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
        if(mCmd == CMD_MODEL) menu.add(0, DELETE_ID, 0, getString(R.string.deletePower));
        menu.add(0, DELETEITEM_ID, 0, getString(R.string.deletePowerItem));
        menu.add(0, EDIT_ID, 0, getString(R.string.edit));
        menu.add(0, STATISTIC_ID, 0, getString(R.string.statistic));
	}
    
    /***************************************************************************/
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	super.onListItemClick(l, v, position, id);
        
    	if(mCmd == CMD_MODEL){
	    	launchChrono(id);   		
    	}else if(mCmd == CMD_FIND){
    		Intent intent = new Intent();
			intent.putExtra(TablePower.COL_POWER_ITEM_ID,id);
			setResult(RESULT_OK, intent);
			finish();
    	}

    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case NEW_POWER_ID:
        	createPower();
            return true;
        case FIND_POWER_ID:
            findPower();
            return true;
        case FIND_POWER_ALL:
            findPowerAll();
            return true;
	    }        
        return super.onMenuItemSelected(featureId, item);
    }
	@Override
	public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		final long powerItemID = resolvePowerItemId(info.id);
    	
    	switch(item.getItemId()) {
	    	case DELETE_ID:
		        mDbTablePower.setId(info.id);
		        mDbTablePower.delete();
		        populateFields();
		        return true;
	    	case DELETEITEM_ID:
	    		
	    		mDbTablePowerItem.setId(powerItemID);
	    		mDbTablePowerItem.load();
	    		
	    		Make.dialogConfirm(this,getText(R.string.delete)+" "+mDbTablePowerItem.getName()+"?")
		        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		        	public void onClick(DialogInterface dialog, int whichButton) {
		        		
		        		mDbAdapter.deletePowerItem(powerItemID);
				    	populateFields();
				    	
		        	}
		        }).create().show();
	    		
		        return true;
		    case EDIT_ID:
		        launchEdit(powerItemID);
		        return true;
		    case STATISTIC_ID:
		        launchStatistic(powerItemID);
		        return true;
		}
		return super.onContextItemSelected(item);
	}
	
	private long resolvePowerItemId(long id) {
		long powerItem;
		if(mCmd == CMD_MODEL){
			mDbTablePower.setId(id);
		    mDbTablePower.load();
			powerItem = mDbTablePower.getPowerItemId();	
		}else powerItem = id ;
		return powerItem;
	}
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        switch(requestCode) {
	        case ACTIVITY_NEW:
	        	if(resultCode == RESULT_OK){
	        		long powerItemId = intent.getExtras().getLong(TablePowerItem.COL_ROW_ID);
	        		saveData(powerItemId);
	        	}
	            break;
	        case ACTIVITY_FIND:
	        	if(resultCode == RESULT_OK){
	        		long powerItemId = intent.getExtras().getLong(TablePower.COL_POWER_ITEM_ID);
	        		saveData(powerItemId);
	        	}
	            break;
	        	
        }
	    populateFields();
    }
    
	private void saveData(long powerItemId) {
		mDbTablePower.setId(0);
		mDbTablePower.setPowerItemId(powerItemId);
		mDbTablePower.setModelId(mModelId);
		mDbTablePower.save();
	}
	
    public class PowerAdapter extends BaseAdapter{
    	
        private Context mContext;
        private Cursor mCursor;
        
    	public PowerAdapter(Context c ,Cursor cursor) {
            mContext = c;
            mCursor = cursor;
		}
    	
		@Override
		public int getCount() {
			return mCursor.getCount();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			mCursor.moveToPosition(position);
            return mCursor.getLong(mCursor.getColumnIndexOrThrow(TableModel.COL_ROW_ID));
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater factory = LayoutInflater.from(mContext);
			View view = factory.inflate(android.R.layout.simple_list_item_2, null);
			
			TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
			TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
			
			mCursor.moveToPosition(position);
			mDbTablePowerItem.loadCursor(mCursor);
			
			String desc = mDbTablePowerItem.getCapacity()+"mAh ";
			desc += mDbTablePowerItem.getVoltage()+"v ";
				
			String name = mDbTablePowerItem.getName();
			
			tv1.setText(name);
			tv2.setText(desc);
						
			return view;
		}
    	
    }
    
}